package com.xixi.demo.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTUtils {
    private static long expiration = 24 * 60 * 60 * 1000;
    //生成的密钥
    private static String secretString = "7M0748WpGV9zJ6uaelq54QCi4lGq5E7F2jEnk49cm6w=";
    //生成安全密钥
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    /**
     * 生成令牌
     * @param claims
     * @return
     */
    public static String genJwt(Map<String, Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key)
                .compact();

    }

    /**
     * 校验令牌
     * @param token
     */
    public static Claims verify(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();

        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            log.error("token失效, token:"+token);
        }catch(Exception e){
            log.error("token校验失败, token:"+token);
        }
        return claims;
    }

    /**
     * 从token中获取当前用户
     * @param token
     * @return
     */
    public static Integer getUserIdFromToken(String token){
        Claims claims = verify(token);
        Assert.notNull(claims, "token不合法");
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
